import * as React from 'react';
import {
    View,
    Text,
    DatePickerAndroid,
    Image,
    DatePickerIOS,
    Platform,
    StyleSheet,
    TouchableOpacity
} from 'react-native';

interface IDatePickerProps {
    _style: any,
    onDateChange(dateStr: string): any
}

class DatePicker extends React.Component<IDatePickerProps>{
    constructor(props) {
        super(props);
        this.state = { chosenDate: new Date() };
        this.setDate = this.setDate.bind(this);
    }

    setDate(newDate) {
        this.setState({chosenDate: newDate})
    }

    async showAndroid() {
        try {
          const {
            action,
            year,
            month,
            day
          } = await DatePickerAndroid.open({
            date: new Date()
          });
          if (action !== DatePickerAndroid.dismissedAction) {
            this.props.onDateChange(year + '-' + month + '-' + day)
          }
        } catch ({ code, message }) {
          console.warn('Cannot open date picker', message);
        }
      }

    public render() {
        const url = 'http://120.48.109.211:8088/static/icon/calendar.png'
        const picker = Platform.OS === 'iOS' ?
        <View >
          <Text styles={this.props._style}>{this.props.hint}</Text>
          <DatePickerIOS
            date={this.state.chosenDate}
            onDateChange={this.setDate}
          /> 
        </View>
        :
        <View style={this.props._style}>
          <TouchableOpacity 
            onPress={()=>{
              this.showAndroid()
            }}
           >
            <Image
              style={{width: 28, height: 28,}}
              source={{ uri: url }}
            />
          </TouchableOpacity>
        </View>
        return (
          <View>
            {picker}
          </View>
        )
    }
}

export default DatePicker